/**
 * @File Name: epoller.cpp
 * @brief  Epoller 类的实现
 * @Author : beyon_sir email:caoboyang.chn@gmail.com
 * @Version : 1.0
 * @Create Date : 2022-11-20
 * 
 */
#include "epoller.h"

/// @brief 初始化 epollfd 和 events_ 
/// @param maxEvent 
Epoller::Epoller(int maxEvent):epollFd_(epoll_create(512)), events_(maxEvent){
    // epollfd 直接通过epoll_create(512) 返回值获取
    // events_ 初始化 size大小为maxEvent
    assert(epollFd_ >= 0 && events_.size() > 0);
}

/// @brief 关闭epollfd_
Epoller::~Epoller() {
    close(epollFd_);
}

/// @brief 向eventpull 中加入新的检测事件 
/// @param fd 
/// @param events 
/// @return 
bool Epoller::AddFd(int fd, uint32_t events) {
    if(fd < 0) return false;
    epoll_event ev = {0};
    ev.data.fd = fd;        // 要检测的对象fd
    ev.events = events;     // 要检测的事件
    return 0 == epoll_ctl(epollFd_, EPOLL_CTL_ADD, fd, &ev);
}

/// @brief 向eventpull 中修改某个fd的检测信息 
/// @param fd 
/// @param events 
/// @return 
bool Epoller::ModFd(int fd, uint32_t events) {
    if(fd < 0) return false;
    epoll_event ev = {0};
    ev.data.fd = fd;
    ev.events = events;
    return 0 == epoll_ctl(epollFd_, EPOLL_CTL_MOD, fd, &ev);
}

/// @brief 向eventpull 中删除检测事件 
/// @param fd 
/// @return 
bool Epoller::DelFd(int fd) {
    if(fd < 0) return false;
    epoll_event ev = {0};
    return 0 == epoll_ctl(epollFd_, EPOLL_CTL_DEL, fd, &ev);
}

/// @brief 调用内核检测事件
/// @param timeoutMs 
/// @return 
int Epoller::Wait(int timeoutMs) {
    return epoll_wait(epollFd_, &events_[0], static_cast<int>(events_.size()), timeoutMs);
}

/// @brief 根据索引i获取对应检测事件的文件描述符fd
/// @param i 
/// @return 
int Epoller::GetEventFd(size_t i) const {
    assert(i < events_.size() && i >= 0);
    return events_[i].data.fd;
}

/// @brief 根据索引i获取对应检测事件的epoll_event
/// @param i 
/// @return 
uint32_t Epoller::GetEvents(size_t i) const {
    assert(i < events_.size() && i >= 0);
    return events_[i].events;
}